﻿
using System;
using System.Web;
using System.Collections.Generic;
using Chenxin.Lib.Passport.Entity;
using Chenxin.Lib.Passport.BLL;
using Chenxin.Lib.Utility;
using System.Text;
using System.Data;

/// <summary>
///AjaxHandlerBase 的摘要说明
/// </summary>
public class AjaxHandlerBase : IHttpHandler
{
    /// <summary>
    /// 自动检查权限
    /// </summary>
    virtual public bool IsAutoCheckPermit
    {
        get { return true; }
    }

    public AjaxHandlerBase()
	{
        //处理类型权限组合实例化
        htTypePermit = new System.Collections.Hashtable();
	}

    //用户信息
    private Chenxin.Lib.Passport.BLL.Cache_UserInfo _customerInfo;
    //处理类型权限组合
    protected System.Collections.Hashtable htTypePermit;

    //用户信息属性
    public Chenxin.Lib.Passport.BLL.Cache_UserInfo CurrentUserInfo
    {
        get { return _customerInfo; }
        set { _customerInfo = value; }
    }

    //IHttpHandler接口方法实现
    public void ProcessRequest(HttpContext context)
    {
        //用户信息
        _customerInfo = GetCurrentUserInfo(context);

        //权限检查新模式，配合弹出层事先权限检查
        //添加人：熊世宏
        //添加日期：2010-05-04
        if (IsAutoCheckPermit&&context.Request["op"] != null)
        {
            if (!CheckPermit(context))
            {
                return;
            }
        }
        //子类实现
        RequestProcess(context);
        return;


        /*
         * edit by kimi 2010-5-5
        //预先权限判断
        if (IsAutoCheckPermit)
        {
            if (!preChkPermit(context))
            {
                return;
            }
        }
        //子类实现
        RequestProcess(context);*/
    }

    //IHttpHandler接口属性实现
    virtual public bool IsReusable
    {
        get
        {
            return false;
        }
    }
    //*******************************************
    //功能概要       ：子类中必须进行重写的方法
    //参数説明       ：context 会话上下文
    //返回值説明     ：无
    //功能詳細       ：实现主要的业务逻辑的方法
    //作成者         ：he.jifeng 
    //作成日         ：2010-02-26 
    //*******************************************
    virtual public bool preChkPermit(HttpContext context)
    {
        bool bRet = true;
        //操作类型
        string strType = context.Request.Params["op"];
        //Dubug中。。。。。暂时不处理
        //////////////////////////////////////////////
        if (strType == null)
        {
            return bRet;
        }
        //////////////////////////////////////////////
        //处理类型为判断权限
        if (strType.ToLower() == "chkpermit")
        {
            return CheckPermitForAjax(context);
        }
        //操作类型存在判断
        if (htTypePermit.ContainsKey(strType))
        {
            //权限有无判断
            if (!_customerInfo.ContainsPermit(htTypePermit[strType].ToString()))
            {
                context.Response.Write(retExecResult(Constants.ExecResult.Error, "没有相应权限，请与管理员联系", ""));
                bRet = false;
            }
        }

        return bRet;
    }

    //*******************************************
    //功能概要       ：子类中必须进行重写的方法
    //参数説明       ：context 会话上下文
    //返回值説明     ：无
    //功能詳細       ：实现主要的业务逻辑的方法
    //作成者         ：he.jifeng 
    //作成日         ：2010-02-26 
    //*******************************************
    virtual public void RequestProcess(HttpContext context) { }

    //*******************************************
    //功能概要       ：获得用户信息
    //参数説明       ：无
    //返回值説明     ：用户信息
    //功能詳細       ：获得用户信息
    //作成者         ：he.jifeng 
    //作成日         ：2010-02-26 
    //*******************************************
    private Cache_UserInfo GetCurrentUserInfo(HttpContext context)
    {
        //Cookie中保存的键标示
        if (context.Request.Cookies["requestkey"] == null)
        {
            context.Response.Write(string.Format("{{success:'-1',msg:'{0}',data:''}}", "用户登录已过期，请重新登录(lost cookie)"));
            context.Response.End();
            return null;
        }
        string strCookieVal = context.Request.Cookies["requestkey"].Value;
        //Cache中对应的键值
        string strKeyUserId = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_REQUEST, strCookieVal);
        //用户Id
        string strUserId;

        Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);

        //从Cookies取得用户Id
        strUserId = cs.GetString(strKeyUserId);
        if (!cs.Hit)
        {
            context.Response.Write(string.Format("{{success:'-1',msg:'{0}',data:''}}", "用户登录已过期，请重新登录(no cache)"));
            context.Response.End();
            return null;
        }

        //用户基本信息业务类
        Chenxin.Lib.Passport.BLL.Cache_UserInfo bllCacheUserInfo = new Chenxin.Lib.Passport.BLL.Cache_UserInfo(new Guid(strUserId));
        //得到当前用户信息
        return bllCacheUserInfo.GetCurrentUserInfo();
    }

    //*******************************************
    //功能概要       ：单独的权限判断
    //参数説明       ：context 请求的上下文
    //返回值説明     ：有无权限
    //功能詳細       ：单独的权限判断
    //作成者         ：he.jifeng 
    //作成日         ：2010-04-01
    //*******************************************
    virtual public bool CheckPermitForAjax(HttpContext context)
    {
        string strPermit = context.Request.Params["Permit"];
        //响应字符串
        string strRet;
        //权限判断
        if (!CurrentUserInfo.ContainsPermit(strPermit))
        {
            strRet = retExecResult(Constants.ExecResult.Error, "没有相应权限，请与管理员联系", "");
            context.Response.Write(strRet);
            return false;
        }
        else
        {
            strRet = retExecResult(Constants.ExecResult.Succ, "OK", "");
            context.Response.Write(strRet);
            return false;
        }
    }

    //*******************************************
    //功能概要       ：返回Json数据结构
    //参数説明       ：execRet 执行结果
    //               ：strMsg  结果消息
    //               ：strData 返回数据
    //返回值説明     ：返回Json数据
    //功能詳細       ：返回Json数据结构
    //作成者         ：he.jifeng 
    //作成日         ：2010-03-31
    //*******************************************
    public string retExecResult(Constants.ExecResult execRet, string strMsg, object objData)
    {
        StringBuilder strRet = new StringBuilder();
        strRet.Append("{");
        strRet.Append("success:'" + ((int)execRet).ToString() + "',");
        strRet.Append("msg:" + Chenxin.Lib.Utility.JsonHelp.Convert2Json(strMsg) + ",");
        strRet.Append("data:" + Chenxin.Lib.Utility.JsonHelp.Convert2Json(objData));
        strRet.Append("}");

        return strRet.ToString();
    }

    /// <summary>
    /// 添加附件
    /// </summary>
    /// <param name="strPath"></param>
    /// <returns></returns>
    virtual public void AddAttachments( Guid RecordId, string strPath, string strFileName, int FileType)
    {
        
        Chenxin.Lib.Hr.Entity.Attachment entAtt;
        string[] FileNames = strFileName.Split(',');
        string[] Paths = strPath.Split(',');

        for (int idxCnt = 0; idxCnt < FileNames.Length; idxCnt++)
        {
            entAtt = new Chenxin.Lib.Hr.Entity.Attachment();
            entAtt.RecordId = Guid.NewGuid();
            entAtt.RelationId = RecordId;
            entAtt.Type = FileType;
            entAtt.Path = Paths[idxCnt];
            entAtt.FileName = FileNames[idxCnt];
            entAtt.UserId = CurrentUserInfo.UserId;
            entAtt.UserName = CurrentUserInfo.UserName;
            entAtt.CityId = CurrentUserInfo.CityId;
            entAtt.CityName = CurrentUserInfo.CityName;
            entAtt.CompanyId = CurrentUserInfo.CompanyId;
            entAtt.CompanyName = CurrentUserInfo.CompanyName;

            Chenxin.Lib.Hr.BLL.Attachment.Add(entAtt);
        }
    }
    /// <summary>
    /// 删除附件
    /// </summary>
    /// <param name="strPath"></param>
    /// <returns></returns>
    virtual public void DelAttachments( HttpContext context, Guid RecordId)
    {
        Chenxin.Lib.Hr.Entity.Attachment entAtt = Chenxin.Lib.Hr.BLL.Attachment.GetModel(RecordId);

        string savePath = context.Server.MapPath(Constants.DIRECTORY + entAtt.Path);

        if (System.IO.File.Exists(savePath))
        {
            System.IO.File.Delete(savePath);
        }

        Chenxin.Lib.Hr.BLL.Attachment.Delete(RecordId);
    }

    /// <summary>
    /// 保存文件
    /// </summary>
    /// <param name="context">请求上下文</param>
    virtual public void Fileupload(HttpContext context, string strFile)
    {
        try
        {
            Random rd = new Random();
            HttpPostedFile file = context.Request.Files["FileData"];

            string savePath = context.Server.MapPath(Constants.DIRECTORY + strFile);
            string fileName = file.FileName.ToString();
            string saveName = DateTime.Now.ToString("yyyyMMddhhmmss") + rd.Next(100, 999).ToString() + fileName.Substring(fileName.LastIndexOf('.'));

            if (file != null)
            {
                if (!System.IO.Directory.Exists(savePath))
                {
                    System.IO.Directory.CreateDirectory(savePath);
                }
                file.SaveAs(savePath + saveName);
                context.Response.Write(string.Format("{{success:1,msg:'文件上传成功！',data:{{filename:'{0}',savename:'{1}'}}}}", fileName, saveName));
            }
            else
            {
                context.Response.Write(retExecResult(Constants.ExecResult.Error, "文件上传失败，请重试！", ""));
            }
        }
        catch (Exception ex)
        {
            context.Response.Write(retExecResult(Constants.ExecResult.Error, ex.Message, ""));
        }

    }

    /// <summary>
    /// 添加跟单
    /// </summary>
    /// <returns></returns>
    public void AddTrace(Chenxin.Lib.House.Entity.House_TraceInfo house_TraceInfo)
    {
        //添加跟单记录
        house_TraceInfo.TraceId = Guid.NewGuid();
        //0=系统，10=电话，20=看房，30=拜访，40=其他
        if (house_TraceInfo.TraceType==null)
            house_TraceInfo.TraceType = 0;
        //跟单内容	 
        if (!String.IsNullOrEmpty(house_TraceInfo.TraceContext))
        house_TraceInfo.TraceContext = house_TraceInfo.TraceContext.Replace("\r", "\\r");
        //跟单人Id	 
        house_TraceInfo.TractorId = CurrentUserInfo.UserId;
        //跟单人	 
        house_TraceInfo.Tractor = CurrentUserInfo.UserName;
        //跟单部门Id	 
        house_TraceInfo.DepartId = CurrentUserInfo.DepartId;
        //跟单部门	 
        house_TraceInfo.Depart = CurrentUserInfo.DepartName;
        //跟单公司
        house_TraceInfo.CompanyId = CurrentUserInfo.CompanyId;
        //跟单公司名	 
        house_TraceInfo.CompanyName = CurrentUserInfo.CompanyName;
        //跟单城市 
        house_TraceInfo.CityId = CurrentUserInfo.CityId;
        //跟单城市名	 
        house_TraceInfo.CityName = CurrentUserInfo.CityName;
        //0=房源跟单，1=客源跟单 默认为房源跟单
        if (house_TraceInfo.status ==null)
            house_TraceInfo.status = 0;
        //是否显示跟单 0：显示；1：不显示
        if (!house_TraceInfo.IsHide)
        house_TraceInfo.IsHide = false;
        //跟单时间
        house_TraceInfo.TraceTime = DateTime.Now;
        Chenxin.Lib.House.DAL.House_TraceInfo.Add(house_TraceInfo);
    }


    /// <summary>
    /// 权限检查，匹配权限检查新模式适用
    /// 添加人：熊世宏
    /// 添加日期：2010-05-04
    /// </summary>
    /// <param name="context">会话</param>
    /// <returns>
    /// 返回true表示数据操作权限检查，程序将继续执行
    /// 返回false表示事先权限检查，程序自动跳出
    /// </returns>
    public bool CheckPermit(HttpContext context)
    {
        //权限判断
        bool isShowCheck = false;
      
        if (context.Request["code"] != null && context.Request["op"].ToLower().Contains("checkpermit"))//操作前，特定的权限检查，弹出层等
        {
            isShowCheck = true;
            //检查哈希表中时候添加对应键值，根据操作类型判断权限
            if (htTypePermit.ContainsKey(context.Request["code"].ToLower()))
            {
                //hasPermit = CurrentUserInfo.ContainsPermit(htTypePermit[context.Request["code"].ToLower()].ToString()).ToString().ToLower();
                if (CurrentUserInfo.ContainsPermit(htTypePermit[context.Request["code"].ToLower()].ToString()) == false) //无基本操作权限
                {
                    context.Response.Write("{success:0,msg:'操作失败，您无此权限，请联系管理员！',data:{permit:false}}");
                    return false;
                }
            }
        }
        else//没有进行事先的权限检查执行的操作，例如：直接点击按钮进行后台交互的
        {
            isShowCheck = false;
            //操作类型判断
            if (htTypePermit.ContainsKey(context.Request["op"].ToLower()))
            {
                //没有操作权限
                if (!CurrentUserInfo.ContainsPermit(htTypePermit[context.Request["op"].ToLower()].ToString()))
                {
                    context.Response.Write("{success:0,msg:'操作失败，您无此权限，请联系管理员！',data:{permit:false}}");
                    return false;
                }
            }
        }

        string checkMsg = "";
        bool bSuccess = CustomerCheckPermint(context, out checkMsg);

        if (isShowCheck)//是否是弹出层的判断
        {
            context.Response.Write(checkMsg);
            return false;
        }
        else
        {
            if (!bSuccess) {
                context.Response.Write(checkMsg);
            }

            return bSuccess;
        }
    }

    /// <summary>
    /// 用户自定义权限验证，子类重写；
    /// 返回权限字符串：
    /// 普通返回"true"或"false"字符串；
    /// 如果有多个权限，可用Json字符串进行返回；
    /// 例如："{a:true,b:false,c:true}"
    /// 
    /// 添加人：熊世宏
    /// 添加日期：2010-05-04
    /// </summary>
    /// <param name="context">会话</param>
    /// <returns></returns>
    public virtual bool CustomerCheckPermint(HttpContext context, out string strMsg)
    {
        strMsg = "{success:1,msg:'',data:{permit:true}}";
        return true;
    }

    /// <summary>
    /// 权限检查，确定所拥有的操作
    /// 添加人：chenyugong
    /// 添加日期：2010-06-13
    /// </summary>
    /// per ： 权限项
    /// confine：用户所在层级
    /// op：checkDepart 组织架构表中的设定
    /// strMsg：消息
    /// <returns>
    /// 返回true表示数据操作权限检查，程序将继续执行
    /// 返回false表示事先权限检查，程序自动跳出
    /// </returns>
    public bool CheckPermint(System.Collections.Hashtable per,System.Collections.Hashtable confine,bool checkDepart, out string strMsg)
    {
         //权限判断
        if (CurrentUserInfo.ContainsPermit(per["ALL"].ToString()))
        {
            strMsg = "{success:1,msg:'',data:{permit:true}}";
            return true;
        }
        else if (CurrentUserInfo.ContainsPermit(per["CITY"].ToString()))
        {
            if (CurrentUserInfo.CityId.Equals((Guid)confine["CityId"]))
            {
                strMsg = "{success:1,msg:'',data:{permit:true}}";
                return true;
            }
            else
            {
                strMsg = "{success:1,msg:'操作失败，您无此权限，请联系管理员！',data:{permit:false}}";
                return false;
            }
        }
        else if (CurrentUserInfo.ContainsPermit(per["COMPANY"].ToString())) 
        {
            if (CurrentUserInfo.CompanyId.Equals((Guid)confine["CompanyId"]))
            {
                strMsg = "{success:1,msg:'',data:{permit:true}}";
                return true;
            }
            else
            {
                strMsg = "{success:1,msg:'操作失败，您无此权限，请联系管理员！',data:{permit:false}}";
                return false;
            }
        }
        else if (CurrentUserInfo.ContainsPermit(per["DEPART"].ToString()))
        {
            if (checkDepart)
            {
                strMsg = "{success:1,msg:'',data:{permit:true}}";
                return true;
            }
            else
            {
                strMsg = "{success:1,msg:'操作失败，您无此权限，请联系管理员！',data:{permit:false}}";
                return false;
            }
        }
        else
        {
            if (CurrentUserInfo.UserId.Equals((Guid)confine["OperatorId"]))
            {
                strMsg = "{success:1,msg:'',data:{permit:true}}";
                return true;
           /* if (checkDepart)
                {
                    strMsg = "{success:1,msg:'',data:{permit:true}}";
                    return true;
                }
                else
                {
                    strMsg = "{success:1,msg:'操作失败，您无此权限，请联系管理员！',data:{permit:false}}";
                    return false;
                }
            */
            }
            else
            {
                strMsg = "{success:1,msg:'操作失败，您无此权限，请联系管理员！',data:{permit:false}}";
                return false;
            }
        }
    }

    /// <summary>
    /// 自定义行显示方式
    /// </summary>
    /// <param name="columnName">列名</param>
    /// <param name="columnVal">列值</param>
    /// <param name="dr">dr数据记录</param>
    /// <returns></returns>
    public virtual string CustomerRowDefine(string columnName, string columnVal, DataRow dr)
    {
        return columnVal;
    }

    /// <summary>
    /// 生成表格TR
    /// </summary>
    /// <param name="dt">数据源</param>
    /// <param name="columnList">要生成的列，按序生成</param>
    /// <param name="keyName">主键字段名</param>
    /// <returns></returns>
    public string CreateGrid(DataTable dt, string columnList, string keyName)
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        string[] columnAr = columnList.Split(',');

        foreach (DataRow dr in dt.Rows)
        {
            sb.AppendFormat("<tr id=\"{0}\" class=\"x-grid-row\">", Chenxin.Lib.Utility.DatasetHelper.GetValue(dr, keyName, ""));
            foreach (string c in columnAr)
            {
                sb.AppendFormat("<td>{0}</td>", CustomerRowDefine(c, Chenxin.Lib.Utility.DatasetHelper.GetValue(dr, c.Trim(), ""), dr));
            }
            sb.Append("</tr>");
        }
        return sb.ToString();
    }

    /// <summary>
    /// 生成DL行表格
    /// </summary>
    /// <param name="dt"></param>
    /// <param name="columnList"></param>
    /// <param name="keyName"></param>
    /// <returns></returns>
    public string CreateDlGrid(DataTable dt, string columnList, string keyName)
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        string[] columnAr = columnList.Split(',');

        foreach (DataRow dr in dt.Rows)
        {
            sb.AppendFormat("<dl id=\"{0}\" class=\"x-grid-row\">", Chenxin.Lib.Utility.DatasetHelper.GetValue(dr, keyName, ""));
            foreach (string c in columnAr)
            {
                sb.AppendFormat("<dd>{0}</dd>", CustomerRowDefine(c, Chenxin.Lib.Utility.DatasetHelper.GetValue(dr, c.Trim(), ""), dr));
            }
            sb.Append("</dl>");
        }
        return sb.ToString();
    }

    /// <summary>
    /// 添加日志
    /// </summary>
    /// <returns></returns>
    public void AddLog(String context, String type)
    {
        //添加日志
        Chenxin.Lib.Business.Entity.System_TraceInfo Logs = new Chenxin.Lib.Business.Entity.System_TraceInfo();
        Logs.TraceId = Guid.NewGuid();
        Logs.TrackerId = CurrentUserInfo.UserId;
        Logs.TrackerName = CurrentUserInfo.UserName;
        Logs.TraceDepartId = CurrentUserInfo.DepartId;
        Logs.TraceDepart = CurrentUserInfo.DepartName;
        Logs.OprContext = context;
        Logs.TraceType = type;
        Logs.TraceTime = DateTime.Now;
        Chenxin.Lib.Business.DAL.System_TraceInfo.Add(Logs);
    }

    /// <summary>
    /// 导出全部
    /// </summary>
    public void ExportByServce(HttpContext context,string html)
    {
        context.Response.Clear();
        context.Response.Buffer = true;

        context.Response.Charset = System.Text.Encoding.UTF8.WebName;
        context.Response.AppendHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode("导出文件") + ".xls");
        context.Response.ContentEncoding = System.Text.Encoding.UTF8;
        context.Response.ContentType = "application/ms-excel";
        context.Response.Write("<html><head><meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" /></head><body>" + html + "</body></html>");
    }

}
